package com.lzw.service.impl;

import com.lzw.domain.dto.SQLFormat;
import com.lzw.domain.vo.ResponseVO;
import com.lzw.mapper.BoxmessageMapper;
import com.lzw.service.Line6Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Service
public class Line6ServiceImpl implements Line6Service {

    @Autowired
    private BoxmessageMapper mapper;

    /**
     * 生产数量
     */
    private Integer productionNum = 0;

    /**
     * 合格数量
     */
    private Integer qualifiedNum = 0;

    /**
     * 不合格数量
     */
    private Integer unqualifiedNum = 0;

    /**
     * 合格率
     */
    private Double percentOfPass = 0.0;

    /**
     * 日期
     */
    private String t;

    @Override
    public List<ResponseVO> line6GetMsg(String procedureName) {
        //数据库查出来的
        List<SQLFormat> lists = mapper.line6Msg1(procedureName);
        ResponseVO responseVO;
        t = lists.get(0).getT();
        List<ResponseVO> returnVOS = new ArrayList<>();
        //计数器
        int i = 0;
        for (SQLFormat list : lists) {
            if (t.equals(list.getT())) {
                //证明是同一天的数据
                if ((list.getName().equals("总产量") || list.getName().equals("生产数量")) && list.getValue() > 0) {
                    productionNum = list.getValue();
                    i++;
                    continue;
                }
                if ((list.getName().equals("不合格数") || list.getName().equals("不合格")) && list.getValue() > 0) {
                    unqualifiedNum = list.getValue();
                }
                qualifiedNum = productionNum - unqualifiedNum;
                if (productionNum != 0) {
                    //合格率=合格数量/生产数量，保留两位小数
                    BigDecimal bigDecimal1 = BigDecimal.valueOf(qualifiedNum * 100);
                    BigDecimal bigDecimal2 = BigDecimal.valueOf(productionNum);
                    BigDecimal divide = bigDecimal1.divide(bigDecimal2, 2, RoundingMode.HALF_UP);
                    percentOfPass = divide.doubleValue();
                }
            }
            if (!lists.get(i + 1).getT().equals(t)) {
                responseVO = new ResponseVO(t, list.getAlias(), productionNum, qualifiedNum, unqualifiedNum, percentOfPass);
                returnVOS.add(responseVO);
                productionNum = 0;
                qualifiedNum = 0;
                unqualifiedNum = 0;
                percentOfPass = 0.0;
            }
            i++;
            t = lists.get(i).getT();
            //防止数组下标越界，反正50条数据有多的，最后一条数据错了也没关系，哈哈
            if (i >= 48) i = 47;
        }
        return returnVOS;
    }
}
